<template>
  <div class="app-container">
    <searchForm
      :formOptions="formOptions"
      @onSearch="onSearch"
      @onReset="onReset"
      :formLabelWidth="formLabelWidth"
      v-show="showSearch"
    />

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basic:duties:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basic:duties:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:duties:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="roleList" @selection-change="handleSelectionChange" v-loading="loading">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="注册号" prop="registerCode" align="center" />
      <el-table-column label="学号" prop="sno" :show-overflow-tooltip="true" align="center" />
      <el-table-column label="姓名" prop="name" align="center" />
      <el-table-column label="所在院系" prop="deptNames" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="专业" prop="speciality" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="班级" prop="className" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="年级" prop="gradeName" align="center" />
      <el-table-column label="担任职务" prop="holdOffice" align="center"> 
        <template slot-scope="scope">
          <dict-tag :options="dict.type.basic_stu_duties" :value="scope.row.holdOffice"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="起始时间" prop="startTime" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:duties:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basic:duties:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="60%"
      append-to-body
      @close="CloseIn"
      destroy-on-close
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="注册号" prop="registerCode">
              <el-input v-model.trim="form.registerCode" placeholder="请输入注册号" maxlength="30" :disabled="editDisabled"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name" >
              <el-input 
                v-model.trim="form.name"
                placeholder="请输入姓名"
                @blur="getStudent"
                maxlength="10" :disabled="editDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学号" prop="sno">
              <el-input v-model.trim="form.sno" placeholder="请输入学号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在院系" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择" clearable class="elSelect" @change="handleChange" disabled style="width: 100%">
                <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName"
                  :value="item.deptId" ></el-option>
              </el-select>
              <!-- <el-cascader
                ref="cascaderAddr"
                v-model="form.deptId"
                :options="deptOptions"
                style="width: 100%"
                clearable
                :props="{value: 'id',currentLabels: 'label',checkStrictly: true}"
                @change="handleChange"
                disabled
              ></el-cascader> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="specialityName">
              <el-input v-model.trim="form.specialityName" placeholder="请输入专业" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年级" prop="gradeName">
              <el-input v-model.trim="form.gradeName" placeholder="请输入年级" disabled />

             
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="className">
           
              <el-input v-model.trim="form.className" placeholder="请输入班级" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="担任职务" prop="holdOffice">
              <el-select v-model="form.holdOffice" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.basic_stu_duties"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="date"
                placeholder="选择起始时间"
                style="width:100%"
                clearable
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptTreeSelect } from "@/api/system/user";
import {
  dutiesList,
  addDuties,
  updataDuties,
  dutiesInfor,
  delDuties
} from "@/api/information/studentPosition";

import { getGradeSelect } from "@/api/information/gradeInfor";
import { getDicts } from "@/api/system/dict/type";
import { queryStudent,collegeSelect } from "@/api/information/studentInfor";
import { getSpecialityByDeptId } from "@/api/information/unitMajor";
import searchForm from "@/components/Search/searchForm.vue";
import Validators from "@/utils/validate.js";
export default {
  name: "Role",
  dicts: [
    "basic_stu_duties" // 学生担任职务字典
  ],
  components: { searchForm },
  data() {
    return {
      dutiesList: [],
      // 遮罩层
      loading: true,
      formLabelWidth: "80px",
      editDisabled: false,
      formOptions: [
        {
          label: "专业名称",
          prop: "speciality",
          element: "el-input",
          placeholder: "请输入专业名称"
        },
        {
          label: "班级",
          prop: "className",
          element: "el-input",
          placeholder: "请输入班级"
        },
        {
          label: "学号",
          prop: "sno",
          element: "el-input",
          placeholder: "请输入学号"
        },
        {
          label: "担任职务",
          prop: "holdOffice",
          element: "el-select",
          options: this.dutiesList,
          placeholder: "请选择担任职务"
        }
      ],
      // 选中数组
      ids: [],
      name: [],
      // 非单个禁用
      single: true,
      // 入学年级数据
      gradeList: [],
      classList: [], // 获取班级
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      specialityDisabled: true, // 专业禁用
      classDisabed: true, // 班级禁用
      // 专业数据
      professionList: [],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        registerCode: [
          { required: true, message: "注册号不能为空", trigger: "blur" }
        ],
        name: [
          {
            required: true,
            text: "请输入姓名",
            validator: Validators.isString,
            trigger: "blur"
          }
        ],
        sno: [{ required: true, message: "学号不能为空", trigger: "blur" }],
        deptId: [
          { required: true, message: "请选择所在院部", trigger: "change" }
        ],
        speciality: [
          { required: true, message: "请选择专业", trigger: "blur" }
        ],
        gradeName: [{ required: true, message: "请选择年级", trigger: "bulr" }],
        className: [{ required: true, message: "请选择班级", trigger: "bulr" }],
        holdOffice: [
          { required: true, message: "请选择担任职务", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "请选择起始时间", trigger: "change" }
        ]
      }
    };
  },

  created() {
    this.getList();
    getDicts("basic_stu_duties").then(res => {
      this.formOptions[3].options = res.data.map(item => {
        return {
          value: item["dictValue"],
          label: item["dictLabel"]
        };
      });
    });
  },
  methods: {
    // 获取搜索表单提交的数据
    onSearch(val) {
      // 查询条件和分页数据合并
      this.queryParams = Object.assign(this.queryParams, val);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    onReset(data) {
      this.queryParams = Object.assign(this.queryParams, data);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      dutiesList(this.queryParams).then(response => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 根据注册号查询学生信息
    getStudent() {
      console.log(this.form);
      queryStudent({
        registerOrSno: this.form.registerCode,
        studentName: this.form.name
      }).then(res => {
        console.log(res.data, "学生信息");
        if (res.data) {
          this.form = res.data;
          this.form.studentId = res.data.id;
          this.form.id = undefined;
          // console.log(this.form.studentId,this.form.id)
        }
      });
    },
    // 清除表单
    CloseIn() {
      this.form = {};
      this.open = false;
    },
    // 获取部门信息
    department() {
      collegeSelect().then(res => {
        this.deptOptions = res.data;
        // this.queryParams.deptId = res.data[0].id
      });
    },
    // 获取班级拉下树
    // changeGrade() {
    //   if(this.form.speciality && this.form.gradeId) {
    //     getClassSelect({
    //     gradeId: this.form.gradeId,
    //     specialtyId: this.form.speciality
    //   }).then(res => {
    //     console.log(res, 'grade')
    //     this.classList = res.data;
    //     this.classDisabed = false;
    //   });
    //   }

    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.this.editDisabled = false
    },
    handleChange(value) {
      if (value) {
        this.form.deptId = value[value.length - 1];
        // this.form.multistage = value + "";
        getSpecialityByDeptId({ deptId: this.form.deptId }).then(res => {
          console.log(res);
          this.professionList = res.data;
          this.specialityDisabled = false;
        });
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.name = selection.map(item => item.name);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.editDisabled = false
      this.department();
      this.open = true;
      this.title = "添加学生干部信息";
      getGradeSelect().then(res => {
        console.log(res);
        this.gradeList = res.data;
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.department();
      this.editDisabled = true
      const roleId = row.id || this.ids;
      await dutiesInfor(roleId).then(response => {
        console.log(response, "修改获取详情");
        this.form = response.data;
        this.form.specialityName = response.data.speciality;
        this.open = true;
        this.specialityDisabled = false;
        this.title = "修改学生干部信息";
      });
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      console.log(this.form, "jiii", this.form.id);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updataDuties(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDuties(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id || this.ids;
      this.name = row.name || this.name;
      this.$modal
        .confirm('是否确认删除姓名为"' + this.name + '"的数据项？')
        .then(function() {
          return delDuties(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/basic/duties/export",
        {
          ...this.queryParams
        },
        `role_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>